/**
 * 描述: 业务逻辑处理 - 用户相关接口
 * 作者: 
 * 日期: 
 */


const { querySql, queryOne } = require('../utils/index');
const md5 = require('../utils/md5');
const jwt = require('jsonwebtoken');
const boom = require('boom');
const { SendAuthCode } = require('../utils/sms');
const wxGetOpenIdService = require('../utils/wxGetOpenId');
const driverService = require('../sequelize/control/driverServer')
const { CODE_ERROR, CODE_SUCCESS, PRIVATE_KEY, JWT_EXPIRED } = require('../utils/constant');
const { Token, AppId, AppSecret, Url } = require('../config/index');
const { decode } = require('../utils/user-jwt');
const { es } = require('tencentcloud-sdk-nodejs');
const couponMgrService = require('../sequelize/control/couponMgrService')



//手机验证码
async function activationCode(req, res) {
    let userphone = req.query.phone;
    result = await SendAuthCode(userphone);
    console.log(result);
    if (result.response.Code == 'Ok') {
        res.json({ 'code': '1', 'codeValue': result.code, 'msg': result.response.Message });
    } else {
        res.json({ 'code': '0', 'msg': result.Message });
    }
}



//用户手机号注册
async function userRegister(req, res) {
    let openid = req.cookies.openid || req.query.openid
    let params = { 'phone': req.query.phone, 'openid': openid }
    let result = await driverService.verifyLogin(params);
    console.log(result)
    res.json(result);
}
//用户退出
async function exit(req, res) {
    const result = await driverService.updateOpenId(req.query.phone);
    res.send(result);

}
//用户信息页
async function userInfo(req, res, next) {
    try {
        var openid = req.cookies.openid || req.query.openid;
        var resulter = await driverService.findDriver(openid);
        var loginData = { url: `${Url}`, redirect: "/api/userinfo" };
        var receiptData = {...resulter, url: `${Url}` };
        if (resulter.code == 0) {
            if (resulter.msg) {
                res.send('<h1 style="text-align: center;font-size: 50px;">您还未绑定车牌</h1>')
                return
            }
            res.render('login', loginData);
        } else {
            var token = jwt.sign({ openid },
                PRIVATE_KEY, { expiresIn: JWT_EXPIRED }
            );
            res.cookie('token', token, { signed: false, maxAge: JWT_EXPIRED * 1000, httpOnly: false });
            res.render('receipt', receiptData);
        }
    } catch (error) {
        next(boom.badRequest('错误请求'));
    }

}
//验证用户是否存在openid
function openidIsValid(req, res, next) {
    if (req.cookies.openid || req.query.openid) {
        console.log(req.cookies.openid, req.query.openid);
        next();
    } else {
        wxGetOpenIdService.redirectGetCode(req, res)
    }
}
//使用优惠券
async function couponLogin(req, res) {
    try {
        var openid = req.cookies.openid || req.query.openid;
        var resulter = await driverService.findDriver(openid);
        console.log(resulter)
        var loginData = { url: `${Url}`, redirect: "/api/discountCard" };
        var ctimesData = {...resulter, Direction: parseInt(req.query.states), Channel: parseInt(req.query.channel) };
        if (resulter.code == 0) {
            res.render('login', loginData);
        } else if (resulter.code == 1 && req.query.states) {
            let limit_data = await couponMgrService.findOneCouponMgr();
            var limit_flag_in = true;
            var limit_flag_out = true;
            if (limit_data.LimitInLeft > 0) {
                limit_flag_in = false;
            }
            if (limit_data.LimitOutLeft > 0) {
                limit_flag_out = false;
            }
            var token = jwt.sign({ openid },
                PRIVATE_KEY, { expiresIn: JWT_EXPIRED }
            );
            res.cookie('token', token, { signed: false, maxAge: JWT_EXPIRED * 1000, httpOnly: false });
            res.render('ctimes', {...ctimesData, limit_flag_in, limit_flag_out });
        } else {
            res.send('请重新扫码!')
        }
    } catch (error) {
        boom.badRequest('优惠券使用失败');
    }
}
//设置token
function setToken(req, res, next) {
    let openid = req.cookies.openid || req.query.openid;
    const token = jwt.sign({ openid },
        PRIVATE_KEY, { expiresIn: JWT_EXPIRED }
    );
    res.cookie('token', token, { signed: false, maxAge: JWT_EXPIRED * 1000, httpOnly: false });
    next();
}

module.exports = {
    activationCode,
    userRegister,
    exit,
    userInfo,
    openidIsValid,
    couponLogin,
    setToken
}














//         next(boom.badRequest(msg));
//                     // 登录成功，签发一个token并返回给前端
//                     const token = jwt.sign(
//                         // payload：签发的 token 里面要包含的一些数据。
//                         { username },
//                         // 私钥
//                         PRIVATE_KEY,
//                         // 设置过期时间
//                         { expiresIn: JWT_EXPIRED }
//                     )

//                     let userData = {
//                         id: user[0].id,
//                         username: user[0].username,
//                         nickname: user[0].nickname,
//                         avator: user[0].avator,
//                         sex: user[0].sex,
//                         gmt_create: user[0].gmt_create,
//                         gmt_modify: user[0].gmt_modify
//                     };

//                     res.json({
//                         code: CODE_SUCCESS,
//                         msg: '登录成功',
//                         data: {
//                             token,
//                             userData
//                         }
//                     })
//                 }
//             })
//     }
// }